use std::sync::Mutex;
use tauri::{AppHandle, Manager, Runtime, State};
use tokio::time::{sleep, Duration};

// 闯进一个状态管理属性
pub struct PageInitState {
    pub(crate) frontend: bool, // 前端是否初始化
    pub(crate) backend: bool,  // 后端是否初始化
    pub(crate) isloaded: bool, // 亲后端加载完成标志
}

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
pub async fn app_init_complete<R: Runtime>(
    app: AppHandle<R>,
    state: State<'_, Mutex<PageInitState>>,
    task: String,
) -> Result<(), ()> {
    let mut state_lock = state.lock().unwrap();
    if !state_lock.isloaded {
        match task.as_str() {
            "frontend" => state_lock.frontend = true,
            "backend" => state_lock.backend = true,
            _ => panic!("invalid task completed!"),
        }
        if state_lock.backend && state_lock.frontend {
            // 启动窗口
            let splash_window = app.get_webview_window("tokio").unwrap();
            // 主窗口
            let main_window = app.get_webview_window("main").unwrap();
            // 关闭启动窗口
            splash_window.close().unwrap();
            // 显示主窗口
            main_window.show().unwrap();
            state_lock.isloaded = true;
        }
    }

    Ok(())
}

#[tauri::command]
pub async fn server_init_complete(app: AppHandle) -> Result<(), ()> {
    sleep(Duration::from_secs(3)).await;
    println!("Backend setup task completed!");
    app_init_complete(
        app.clone(),
        app.state::<Mutex<PageInitState>>(),
        "backend".to_string(),
    )
    .await?;
    Ok(())
}
